﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WorkerRole1
{
	using System.Collections.Specialized;

	using Microsoft.Samples.ServiceHosting.StorageClient;

	using RetryPolicies = Microsoft.WindowsAzure.StorageClient.RetryPolicies;
	using StorageException = Microsoft.WindowsAzure.StorageClient.StorageException;

	internal static class QueueSamples
	{

		internal static bool RunQueueSamples = true;
		internal static int MessagesReceived;

		internal static void MessageReceived(object sender, MessageReceivedEventArgs e)
		{
			Console.WriteLine("Received message " + e.Message.ContentAsString());
			MessagesReceived++;
		}

		internal static void RunSamples()
		{
			StorageAccountInfo account = null;
			try
			{
				string sampleGuid = (Guid.NewGuid()).ToString("N");
				string name = "queue" + sampleGuid;
				string name2 = "queue2" + sampleGuid;
				string prefix = "prefix" + sampleGuid;
				bool exists = false;
				bool res = false;

				Console.WriteLine("Create queue " + name);
				account = StorageAccountInfo.GetDefaultQueueStorageAccountFromConfiguration();
				QueueStorage queueService = QueueStorage.Create(account);
				queueService.RetryPolicy = Microsoft.Samples.ServiceHosting.StorageClient.RetryPolicies.RetryN(2, TimeSpan.FromMilliseconds(100));
				MessageQueue q = queueService.GetQueue(name);
				res = q.CreateQueue(out exists);
				if (!exists && res)
				{
					Console.WriteLine("Queue " + name + " successfully created.");
				}

				Console.WriteLine("Get all the queues in an account.");
				IEnumerable<MessageQueue> queues = queueService.ListQueues();
				foreach (MessageQueue qu in queues)
				{
					Console.WriteLine(qu.Name);
				}

				Console.WriteLine("Create a number of queues and show continuation listing. This can take a while...");
				int numListSample = 60;
				for (int j = 0; j < numListSample; j++)
				{
					q = queueService.GetQueue(prefix + (Guid.NewGuid()).ToString("N").Substring(0, 10));
					q.CreateQueue();
				}
				queues = queueService.ListQueues();
				List<MessageQueue> l = new List<MessageQueue>(queues);
				Console.WriteLine("The following queues are available:");
				foreach (MessageQueue qu in l)
				{
					Console.WriteLine(qu.Name);
				}

				Console.WriteLine("Find all queues with a given prefix...");
				queues = queueService.ListQueues(prefix);
				l = new List<MessageQueue>(queues);
				Console.WriteLine("Queues with the prefix " + prefix);
				foreach (MessageQueue qu in l)
				{
					Console.WriteLine(qu.Name);
				}

				Console.WriteLine("Delete all queues with the prefix " + prefix);
				foreach (MessageQueue qu in queues)
				{
					Console.WriteLine("Delete queue" + qu.Name);
					qu.Clear();
					qu.DeleteQueue();
				}

				q = queueService.GetQueue(name);
				if (!q.DoesQueueExist())
				{
					Console.WriteLine("Queue '{0}' does not exist");
				}

				Console.WriteLine("Delete queue " + name);
				q.Clear();
				q.DeleteQueue();

				Console.WriteLine("Get queue properties.");
				q = queueService.GetQueue(name2);
				res = q.CreateQueue(out exists);
				if (!exists && res)
				{
					Console.WriteLine("Queue " + name + " successfully created.");
				}
				QueueProperties props = new QueueProperties();
				props = q.GetProperties();
				props.Metadata = new NameValueCollection();
				props.Metadata.Add("meta-sample1", "sample1");
				props.Metadata.Add("meta-sample2", "sample2");
				q.SetProperties(props);
				props = null;
				props = q.GetProperties();
				Console.WriteLine("Queue properties: " + props.Metadata["meta-sample1"] + " " + props.Metadata["meta-sample2"]);

				Console.WriteLine("Put message into the queue.");
				if (q.PutMessage(new Message("<sample>sample message</sample>")))
				{
					Console.WriteLine("Message successfully put into queue.");
				}
				Console.WriteLine("Get message from the queue.");
				Message msg = q.GetMessage();
				Console.WriteLine(msg.ContentAsString());

				Console.WriteLine("Clear all messages from a queue.");
				for (int i = 0; i < 10; i++)
				{
					q.PutMessage(new Message("<sample>" + i + "</sample>"));
				}
				q.Clear();

				Console.WriteLine("Delete a single message.");
				for (int i = 0; i < 10; i++)
				{
					q.PutMessage(new Message("<sample>" + i + "</sample>"));
				}
				Message msg1 = q.GetMessage();
				q.DeleteMessage(msg1);
				q.Clear();

				Console.WriteLine("Automatic reception of messages.");
				q.MessageReceived += MessageReceived;
				q.PollInterval = 500;
				q.StartReceiving();
				for (int i = 0; i < 10; i++)
				{
					q.PutMessage(new Message("<samplemessage>" + i + "</samplemessage>"));
					System.Threading.Thread.Sleep(1000);

				}
				q.StopReceiving();
				q.Clear();
				q.DeleteQueue();

				Console.WriteLine("Queue samples finished successfully.");
			}
			catch (System.Net.WebException we)
			{
				Console.WriteLine("Network error: " + we.Message);
				if (we.Status == System.Net.WebExceptionStatus.ConnectFailure)
				{
					Console.WriteLine("Please check if the queue storage service is running at " + account.BaseUri.ToString());
					Console.WriteLine("Detailed information on how to run the development storage tool " +
									  "locally can be found in the readme file that comes with this sample.");
				}
			}
			catch (StorageException se)
			{
				Console.WriteLine("Storage service error: " + se.Message);
			}
		}
	}
}
